<template>
  <div class="head">
    <div class="headContainer">
      <div class="logo">
        <router-link to="/home">
          <img src="/src/assets/images/headerLogo.png" alt="" />
        </router-link>
      </div>
      <div class="nav">
        <div
          @click="jump('/home')"
          :class="page === '/home' ? 'navActive' : ''"
          class="navItem"
        >
          首页
        </div>
        <div
          @click="jump('/songsheet')"
          :class="page === '/songsheet' ? 'navActive' : ''"
          class="navItem"
        >
          歌单
        </div>
        <div
          @click="jump('/artlist')"
          :class="page === '/artlist' ? 'navActive' : ''"
          class="navItem"
        >
          歌手
        </div>
        <div
          @click="jump('/vip')"
          :class="page === '/vip' ? 'navActive' : ''"
          class="navItem"
        >
          VIP
        </div>
        <div
          @click="jump('/player')"
          :class="page === '/player' ? 'navActive' : ''"
          class="navItem"
        >
          音乐盒
        </div>
        <div
          @click="jump('/download')"
          :class="page === '/download' ? 'navActive' : ''"
          class="navItem"
        >
          客户端
        </div>
        <div @click="toSettled" class="navItem">音乐人入驻</div>
      </div>
      <input type="text" class="navInput" placeholder="请输入歌名、歌词、歌手、或专辑" />
      <i class="iconfont icon-sousuo navSerchIcon"></i>
      <div class="loginRegister" v-if="!isLogin" @click="loginRegisterBox = true">
        登录 / 注册
      </div>
      <span @click="toUser" style="cursor: pointer" v-else>{{ userInfo.nickName }}</span>
    </div>
    <div class="shadow" v-if="loginRegisterBox">
      <div class="loginRegisterBox">
        <div class="logoBox">
          <img src="../../assets/images/logo.svg" alt="" />
        </div>
        <div class="loginRegContainer">
          <div class="closeLogin">
            <span
              class="iconfont icon-guanbi closeLoginIcon"
              @click="loginRegisterBox = false"
            ></span>
          </div>
          <div v-if="isUseUsername" class="loginTel loginReg">
            <p>登录/注册</p>
          </div>
          <div v-else class="loginTel loginReg">
            <p>账号密码登录</p>
          </div>
          <Form class="form" ref="target" v-slot="{ errors }">
            <div v-if="isUseUsername" class="phone loginReg">
              <div>+86</div>
              <Field
                autocomplete="off"
                type="text"
                name="phone"
                v-model="form.phone"
                class="phoneNum"
                :rules="vaPhone"
                placeholder="请输入手机号"
              />
            </div>
            <div v-else class="phone loginReg">
              <Field
                autocomplete="off"
                class="username"
                v-model="form.username"
                type="text"
                name="username"
                :rules="vaUsername"
                placeholder="请输入账号"
              />
            </div>
            <div class="error" v-if="errors.phone">{{ errors.phone }}</div>
            <div class="error" v-if="errors.username">{{ errors.username }}</div>
            <div v-if="isUseUsername" class="code loginReg">
              <Field
                autocomplete="off"
                type="text"
                name="code"
                v-model="form.code"
                :rules="vaCode"
                placeholder="请输入验证码"
              />
              <div>
                <button :disabled="isCodeDisable" @click.stop="sendCode">
                  <span v-if="!isCodeDisable">发送验证码</span>
                  <span v-else>重新发送({{ nextSendTime }})</span>
                </button>
              </div>
            </div>
            <div v-else class="phone loginReg">
              <Field
                autocomplete="off"
                type="password"
                name="password"
                v-model="form.password"
                :rules="vaPassword"
                placeholder="请输入密码"
                class="password"
              />
            </div>
            <div class="error" v-if="errors.code">{{ errors.code }}</div>
            <div class="error" v-if="errors.password">{{ errors.password }}</div>
          </Form>
          <div class="submit loginReg">
            <button @click.stop="loginHandle">登录/注册</button>
          </div>
          <p
            v-if="isUseUsername"
            @click="isUseUsername = true"
            class="useUsername loginReg"
          >
            使用账号登录
          </p>
          <p v-else @click="isUseUsername = false" class="useUsername loginReg">
            使用手机号登录
          </p>
          <div class="other loginReg">
            <div class="useBaidu">
              <i class="iconfont icon-baidu"></i>
              <span>百度账号登录</span>
            </div>
            <div class="useWechat">
              <i class="iconfont icon-weixin"></i>
              <span>微信登录</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, reactive, onMounted, watch } from "vue";
export default defineComponent({
  name: "Header",
});
</script>

<script lang="ts" setup>
import { useRouter, useRoute } from "vue-router";
import { Form, Field } from "vee-validate";
import { ElMessage } from "element-plus";
import axios from "axios";
import { userInfoModel } from "./Header";
import { loginStatus } from "../../store/moduls/Vip/vip";
// 登录状态
const useloginStatus = loginStatus();
// router对象
const router = useRouter();
// 登录注册框是否显示标识
const loginRegisterBox = ref<boolean>(false);
// 是否使用账号密码登录标识
const isUseUsername = ref<boolean>(false);
// 用户是否登录标识
const isLogin = ref<boolean>(useloginStatus.getIsLogin);
// 用户信息
let userInfo = reactive<userInfoModel>({ nickName: "", avatarUrl: "" });
// 路有对象
const route = useRoute();
// 用于验证路由nav高亮
let page = ref<string>(route.path);
// 是否禁用验证码按钮
const isCodeDisable = ref<boolean>(false);
//下次发送验证码剩余时间
let nextSendTime = ref<number>(60);
// 表单验证相关
const form = reactive({
  phone: null,
  username: null,
  password: null,
  code: null,
});
//验证手机号
const vaPhone = (value: string) => {
  if (!value) return "请输入手机号";
  if (!/^1[2-9]\d{9}$/.test(value)) return "请输入正确的手机号";
  return true;
};
//验证验证码
const vaCode = (value: string) => {
  if (!value) return "请输入验证码";
  return true;
};
//验证账号
const vaUsername = (value: string) => {
  if (!value) return "请输入账号";
  return true;
};
//验证密码
const vaPassword = (value: string) => {
  if (!value) return "请输入密码";
  return true;
};

// 跳转页面函数
const jump = (path: string) => {
  router.push(path);
};
// 监视路径
watch(
  () => route.path,
  () => {
    page.value = route.path;
  }
);
// 跳转入驻
const toSettled = () => {
  window.open("https://release.showstart.com/");
};
//点击发送验证码
const sendCode = () => {
  isCodeDisable.value = true;
  let timer = setInterval(() => {
    nextSendTime.value--;
    if (nextSendTime.value === 0) {
      nextSendTime.value = 60;
      isCodeDisable.value = false;
      clearInterval(timer);
    }
  }, 1000);
  //获取验证码接口
  axios({
    method: "GET",
    url: "http://cloud-music.pl-fe.cn/captcha/sent",
    params: {
      phone: form.phone,
    },
  }).then((res) => {
    console.log(res);
  });
};
// 登录
const loginHandle = async () => {
  // 判断是哪种登录方式

  if (isUseUsername.value) {
    //传入验证码即可登录
    const result = await axios({
      method: "GET",
      url: "http://cloud-music.pl-fe.cn/captcha/verify",
      params: {
        captcha: form.code,
        phone: form.phone,
      },
    });
    console.log(result);
  } else {
    //账号密码登录
    const result = await axios({
      method: "GET",
      url: "http://cloud-music.pl-fe.cn/login/cellphone",
      params: {
        phone: form.username,
        password: form.password,
      },
    });
    console.log(result);
    if (result.data.code === 200) {
      ElMessage({
        message: "登录成功！",
        type: "success",
      });
      // 存cookie
      localStorage.setItem("cookie", result.data.cookie);
      localStorage.setItem("uid", result.data.profile.userId);
      localStorage.setItem("nickName", result.data.profile.nickname);
      localStorage.setItem("avatarUrl", result.data.profile.avatarUrl);
      // 关闭登录框
      loginRegisterBox.value = false;
      useloginStatus.login();
      isLogin.value = useloginStatus.getIsLogin;
      // 用户信息赋值
      userInfo.nickName = result.data.profile.nickname;
      userInfo.avatarUrl = result.data.profile.avatarUrl;

      /* axios({
        method: "POST",
        url: "http://cloud-music.pl-fe.cn/user/detail",
        data: {
          uid: localStorage.getItem("uid"),
          cookie: localStorage.getItem("cookie"),
        },
      }).then((res) => {
        console.log(res);
      }); */
    } else {
      if (result.data.code === 400) {
        //判断是否是账号密码错误
        ElMessage({
          message: "账号密码错误",
          type: "error",
        });
      } else {
        ElMessage({
          message: "网络故障",
          type: "error",
        });
      }
    }
  }
};
// 挂载阶段判断是否已登录
onMounted(() => {
  if (localStorage.getItem("nickName")) {
    useloginStatus.login();
    isLogin.value = useloginStatus.getIsLogin;
    userInfo.nickName = localStorage.getItem("nickName") as string;
    userInfo.avatarUrl = localStorage.getItem("avatarUrl") as string;
  }
});
// 点击跳转至个人中心
const toUser = () => {
  router.push("/user");
};
// 退出登录时
watch(
  () => useloginStatus.isLogin,
  () => {
    if (!useloginStatus.isLogin) {
      isLogin.value = useloginStatus.getIsLogin;
    }
  }
);
</script>

<style scoped lang="less">
.head {
  height: 80px;
  box-shadow: 0 3px 5px #eee;
}
.headContainer {
  width: 1200px;
  height: 100%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  color: rgb(144, 147, 153);
  position: relative;
}
.logo {
  width: 120px;
  height: 80px;
  img {
    width: 120px;
    height: 40px;
    padding: 20px 0;
  }
}

.nav {
  display: flex;
  margin-left: 50px;
  height: 100%;
  .navItem {
    margin: 0 20px;
    line-height: 80px;
    height: 100%;
    cursor: pointer;
  }
  .navActive {
    border-bottom: 1px solid #333;
    font-weight: bold;
    color: #333;
  }
}
.navInput {
  width: 320px;
  height: 40px;
  background-color: rgb(248, 248, 248);
  border: 0;
  border-radius: 6px;
  margin: 0 30px;
  outline: none;
  box-sizing: border-box;
  padding-left: 20px;
}
.loginRegister {
  font-size: 14px;
  color: rgb(96, 98, 102);
  cursor: pointer;
}
a {
  text-decoration: none;
}
.navSerchIcon {
  position: absolute;
  right: 120px;
}
.shadow {
  width: 100%;
  height: 100vh;
  position: fixed;
  top: 0;
  background-color: rgba(0, 0, 0, 0.3);
  z-index: 100 !important;
}
.loginRegisterBox {
  width: 640px;
  height: 460px;
  background-color: #fff;
  display: flex;
  position: absolute;
  top: 110px;
  left: 50%;
  transform: translate(-50%);
  border-radius: 4px;
}
.logoBox {
  width: 220px;
  height: 460px;
  background-image: url("../../assets/images/logobg.png");
  display: flex;
  justify-content: center;
  align-items: flex-start;
  img {
    margin-top: 100px;
  }
}
.loginRegContainer {
  width: 420px;
  height: 460px;
}
.closeLogin {
  height: 50px;
  margin: 0 25px;
  position: relative;
}
.closeLoginIcon {
  font-size: 20px;
  font-weight: bold;
  position: absolute;
  bottom: 0;
  right: 0;
  cursor: pointer;
}
.loginReg {
  margin: 0 30px;
}
.loginTel {
  p {
    padding: 20px 0px;
    font-size: 20px;
    color: #606266;
  }
}
.phone {
  padding: 10px 0;
  display: flex;
  .username,
  .password {
    height: 40px;
    width: 360px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding-left: 10px;
    box-sizing: border-box;
    outline: none;
    &::placeholder {
      color: #c0c4cc;
    }
  }
  .phoneNum {
    height: 40px;
    width: 280px;
    border-radius: 0 4px 4px 0;
    border: 1px solid #dcdfe6;
    outline: none;
    padding-left: 10px;
    box-sizing: border-box;
    &::placeholder {
      color: #c0c4cc;
    }
  }
  div {
    display: inline-block;
    width: 80px;
    height: 40px;
    text-align: center;
    box-sizing: border-box;
    border: 1px solid #dcdfe6;
    line-height: 40px;
    color: #9093a6;
    border-right: 0;
    background-color: #f5f7fa;
    border-radius: 4px 0px 0 4px;
    cursor: pointer;
  }
}
.code {
  padding: 10px 0;
  display: flex;
  input {
    height: 40px;
    width: 240px;
    border-radius: 4px 0 0 4px;
    border: 1px solid #dcdfe6;
    outline: none;
    padding-left: 10px;
    box-sizing: border-box;
    &::placeholder {
      color: #c0c4cc;
    }
  }
  div {
    display: inline-block;
    width: 120px;
    height: 40px;
    text-align: center;
    box-sizing: border-box;
    border: 1px solid #dcdfe6;
    line-height: 40px;
    border-left: 0;
    background-color: #f5f7fa;
    border-radius: 0px 4px 4px 0;
    button {
      width: 100%;
      height: 100%;
      border: 0;
      outline: none;
      color: #9093a6;
      background-color: transparent;
      cursor: pointer;
    }
  }
}
.submit {
  padding: 10px 0;
  button {
    width: 100%;
    height: 40px;
    border: 0;
    background-color: #e61925;
    color: #fff;
  }
}
.useUsername {
  font-size: 14px;
  margin-top: 15px;
  color: #909399;
  cursor: pointer;
}
.other {
  display: flex;
  margin-top: 30px;
  .useBaidu {
    width: 50%;
    cursor: pointer;
    i {
      color: #3385ff;
      font-size: 18px;
    }
    span {
      font-size: 14px;
      color: #909399;
      padding-left: 5px;
    }
  }
  .useWechat {
    width: 50%;
    cursor: pointer;
    i {
      color: #03c801;
      font-size: 20px;
    }
    span {
      font-size: 14px;
      color: #909399;
      padding-left: 5px;
    }
  }
}
.error {
  margin: 0 30px;
  font-size: 12px;
  color: red;
}
</style>
